package no.endelighelg.app;

import no.endelighelg.app.JsonVenueAdapter;
import no.endelighelg.app.EHHttpGet;

import android.util.Log;
import android.view.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import org.json.*;

import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

public class Endelighelg extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Button searchButton = (Button)findViewById(R.id.SearchButton);
        searchButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		clickSearchHandler(v);
        	}
        });
        
        final ListView searchList = (ListView)findViewById(R.id.ListView01);
        searchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView adapterView, View view, int position, long arg3) {
        		JsonVenueAdapter adapter = (JsonVenueAdapter) adapterView.getAdapter();
        		JSONObject obj = adapter.getJSONObject(position);
        		try {
        			Intent showVenueIntent = new Intent();
        			showVenueIntent.setClassName("no.endelighelg.app", "no.endelighelg.app.ShowVenue");
        			showVenueIntent.putExtra("name", obj.getString("title"));
        			startActivity(showVenueIntent);
				} catch (JSONException e) {
					e.printStackTrace();
				}
        	}
        });
    }
    
    public void clickSearchHandler(View view) {
    	EHHttpGet http = new EHHttpGet("http://meld.vilhelmk.sol.no/android-test.php");
		JSONArray json = http.getJSONArray();
		
		((ListView) findViewById(R.id.ListView01)).setAdapter(new JsonVenueAdapter(this, json));
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuItem itemNearBy = menu.add(0, Menu.FIRST+1, 0, "I nærheten");
    	MenuItem itemNewPlace = menu.add(0, Menu.FIRST+2, 1, "Nytt sted");
    	return super.onCreateOptionsMenu(menu);
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case Menu.FIRST + 1:
    		Log.i("endelighelg", "Clicked nearby");
    		return true;
    		
    	case Menu.FIRST + 2:
    		Intent newPlaceIntent = new Intent();
    		newPlaceIntent.setClassName("no.endelighelg.app", "no.endelighelg.app.NewVenue");
    		startActivity(newPlaceIntent);
    		return true;
    		
    	default:
    		return super.onOptionsItemSelected(item);
    	}
    }

}

